package vn.vfriends.vbox.facade;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import vn.vfriends.vbox.model.Account;

/**
 *
 * @author tuancn
 */
@Stateless
public class AccountFacade extends AbstractFacade<Account> {
    
    @PersistenceContext(unitName = "vBoxPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
    public AccountFacade() {
        super(Account.class);
    }
    
    public Account createAccount(Account account) {
        super.create(account);
        return account;
    }
    
    public void remove(Integer id) {
        super.remove(super.find(id));
    }
    
    public List<Account> findByUserId(Integer userId) {
        Query query = em.createNamedQuery("Account.findByUserId", Account.class);
        query.setParameter("userId", userId);
        return query.getResultList();
    }
    
    public Account find(Integer userId, String name) {
        Query query = em.createNamedQuery("Account.find", Account.class);
        query.setParameter("userId", userId);
        query.setParameter("name", name);
        List<Account> accountList = query.getResultList();
        if(accountList != null && !accountList.isEmpty())
            return accountList.get(0);
        else
            return null;
    }

    public List<Account> findAccountsNeedRefreshToken(int remainOfTime) {
        String sql = "SELECT * FROM ACCOUNT "
                + "WHERE refresh_token IS NOT NULL AND refresh_token <> \'\' "
                + "AND TIMESTAMPDIFF(SECOND, NOW(), DATE_ADD(refresh_date, INTERVAL expires_in SECOND)) <= " + remainOfTime;
        
        Query query = em.createNativeQuery(sql, Account.class);
        return query.getResultList();
    }
}
